# -*- coding: utf-8 -*-
import sys, os, urllib, urllib2, re
DEVELOP = True
DEVELOP = False
# version="1.1" 2012/07/25

if not DEVELOP:
	import xbmc, xbmcgui, xbmcplugin, xbmcaddon

# Plugin constants 
#__addonname__ = "ipadwallpaers"
#__addonid__ = "plugin.image.ipadwallpapers"
#__addon__ = xbmcaddon.Addon(id=__addonid__)

UserAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
ORDER_LIST = [['0','Most Recent'], ['1','Being Watched'], ['2','Most Viewed'], ['3','Top Rated']]
IPADWALLPAPERS_LIST = ['http://ipad.91.com/wallpapers/', 'http://ipad.91.com/wallpapers/2.shtml', 'http://ipad.91.com/wallpapers/3.shtml']
DUOWAN_5153_LIST = ['http://tu.duowan.com/tag/5153.html']
DUOWAN_32_LIST = ['http://tu.duowan.com/g/32.html']

#if not DEVELOP:
	#Addon = xbmcaddon.Addon( id=os.path.basename( xbmcaddon.Addon.getAddonInfo('path') ) )
	#Addon = xbmcaddon.Addon( id=os.path.basename( os.getcwd() ) )

def GetHttpData(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', UserAgent)
    response = urllib2.urlopen(req)
    httpdata = response.read()
    if response.headers.get('content-encoding', None) == 'gzip':
        httpdata = gzip.GzipFile(fileobj=StringIO.StringIO(httpdata)).read()
    response.close()
    match = re.compile('<meta http-equiv="[Cc]ontent-[Tt]ype" content="text/html; charset=(.+?)"').findall(httpdata)
    if len(match)<=0:
        match = re.compile('meta charset="(.+?)"').findall(httpdata)
    if len(match)>0:
        charset = match[0].lower()
        if (charset != 'utf-8') and (charset != 'utf8'):
            httpdata = unicode(httpdata, charset).encode('utf8')
    return httpdata


def CATEGORIES(page):
	if page==0:
		link = GetHttpData(IPADWALLPAPERS_LIST[0])
		match = re.compile('<a href=".+?" target="_blank"><img class="cover" src="(.+?)" alt="(.+?)".+?</a></p>', re.DOTALL).search(link)
		#match2 = re.compile('src=".+?/ipad/([0-9]{4}/[0-9]{2}/[0-9]{2})/.+?"').search(match.group(1))
		if DEVELOP:
			print match.group(1)
			print match.group(2)
		addDir('iPad美图 - ' + match.group(2),'http://ipad.91.com/wallpapers/',1,match.group(1).strip(),1,0)
		link = GetHttpData(DUOWAN_5153_LIST[0])
		match = re.compile('<li class="box".+?<img src="(.+?)" height=".+?".+?<em><a href=".+?" target="_blank">(.+?)</a>(.+?)</em></li>', re.DOTALL).search(link)
		if DEVELOP:
			print match.group(1)
			print match.group(2)
		addDir('多玩图库 - '+match.group(2)+' ('+match.group(3)+')','http://tu.duowan.com/',1,match.group(1).strip(),2,0)
		link = GetHttpData(DUOWAN_32_LIST[0])
		match = re.compile('<li class="box".+?<img.+?src="(.+?)" height=".+?".+?<em>.+?<a href=".+?" target="_blank">(.+?)</a>(.+?)</em></li>', re.DOTALL).search(link)
		addDir('多玩图库 - '+match.group(2)+' ('+match.group(3)+')','http://tu.duowan.com/',1,match.group(1).strip(),3,0)

	elif page==1:
		for l in IPADWALLPAPERS_LIST:
			link = GetHttpData(l)
			match = re.compile('<li class="wp_list_li peek">(.+?)</li>', re.DOTALL).findall(link)
			if len(match)<=0:
				match = re.compile('<p class="wp_list_txt"><a href="(.+?)" target="_blank">(.+?)</a></p>', re.DOTALL).findall(link)
				for i in match:
					addDir(match(2),match(1),2,match(1),1, 0)
			else:
				for i in range(0,len(match)):
					match1 = re.compile('img class="cover" src="(.+?)" alt="(.+?)"').search(match[i])
					match2 = re.compile('<a href="(.+?)".target="_blank">.+?</p>').search(match[i])
					addDir(match1.group(2),match2.group(1),2,match1.group(1),1, 0)

	elif page==2:
		for l in DUOWAN_5153_LIST:
			link = GetHttpData(l)
			match = re.compile('<li class="box".+?(<span class="fr">.+?<a href=".+?">.+?</em>)</li>', re.DOTALL).findall(link)
			if DEVELOP:
				print match
			for i in range(0,len(match)):
				match1 = re.compile('<em><a href="(.+?)" target=".+?">(.+?)</a>.+?</em>').search(match[i])
				match2 = re.compile('<img src="(.+?)" height=".+?" /></a>').search(match[i])
				match3 = re.compile('<span class="fr">(.+?)</span>').search(match[i])
				if DEVELOP:
					print match1.group(1)
					print match1.group(2)
					print match2.group(1)
				addDir(match1.group(2)+' ('+match3.group(1)+')',match1.group(1),3,match2.group(1),1, 0)
	elif page==3:
		for l in DUOWAN_32_LIST:
			link = GetHttpData(l)
			match = re.compile('<li class="box".+?(<span class="fr">.+?<a href=".+?">.+?</em>)</li>', re.DOTALL).findall(link)
			if DEVELOP:
				print match
			for i in range(0,len(match)):
				match1 = re.compile('<em>[\S\s]+<a href="(.+?)" target=".+?">(.+?)</a>.+?</em>').search(match[i])
				match2 = re.compile('<img.+?src="(.+?)" height=".+?" /></a>').search(match[i])
				match3 = re.compile('<span class="fr">(.+?)</span>').search(match[i])
				if DEVELOP:
					print match1.group(1)
					print match1.group(2)
					print match2.group(1)
				addDir(match1.group(2)+' ('+match3.group(1)+')',match1.group(1),3,match2.group(1),1, 0)



	if not DEVELOP:
		xbmcplugin.endOfDirectory(int(sys.argv[1]))


def SORTMETHOD(url):
	if DEVELOP:
		print url
		print ORDER_LIST
	else:
		change = False
		dialog = xbmcgui.Dialog()
		list = [x[1] for x in ORDER_LIST]
		sel = dialog.select('Sort Order', list)
		if sel != -1:
			order = ORDER_LIST[sel][0]
			change = True
		if change:
			VIDEOLIST(url,1,order)
        
def DUOWANIMAGELIST(url,page):
	link = GetHttpData(url)
	grid = re.compile('<a href="(http://tu.duowan.com.+?grid/.+?)" class="all">.+?</a>').findall(link)
	link = GetHttpData(grid[0])
	allpages = re.compile('href="(.+?grid/.+?page=.+?)">\d+</a>').findall(link)
	matches = re.compile('<li><a href="(http://.+?)" title="(.+?)"><img alt=".+?" src="(http://.+?)".+?</a></li>').findall(link)
	for match in matches:
		if DEVELOP:
			print match
		piclink = GetHttpData(match[0])
		picurl = re.compile('<a href="(http://.+?)" class="full" target="_blank">').search(piclink)
		if DEVELOP:
			print picurl.group(1)
		addLink(match[1],picurl.group(1),3,match[2].strip())

	if DEVELOP:
		print allpages
	for pageurl in allpages:
		if DEVELOP:
			print pageurl
		link = GetHttpData("http://tu.duowan.com"+pageurl)
		matches = re.compile('<li><a href="(http://.+?)" title="(.+?)"><img alt=".+?" src="(http://.+?)".+?</a></li>').findall(link)
		for match in matches:
			if DEVELOP:
				print match
			piclink = GetHttpData(match[0])
			picurl = re.compile('<a href="(http://.+?)" class="full" target="_blank">').search(piclink)
			addLink(match[1],picurl.group(1),3,match[2].strip())

	if not DEVELOP:
		xbmcplugin.endOfDirectory(int(sys.argv[1]))

                       
def IMAGELIST(url,page):
	link = GetHttpData(url)
	match = re.compile('<div id=".+?">.+?var page_count=(.+?);var totalrecord=(.+?);var theLink.+?="(.+?)";').findall(link)
	if DEVELOP:
		print match
	matchname = re.compile('<h1>(.+?)</h1>').findall(link)
	for i in range(int(match[0][0]), int(match[0][1])):
		newurl =  re.sub("_(\d+).shtml", "_"+str(i)+".shtml", url)
		if DEVELOP:
			print newurl
		link = GetHttpData(newurl)
		matchlink = re.compile('<P align=center.+?<IMG\s*src="(.+?)".+?</.+?>').findall(link)
		if len(matchlink)<=0:
			matchlink = re.compile('<P align=center><IMG\s.+?src="(.+?)".+?</P>').findall(link)
		if len(matchlink)<=0:
			matchlink = re.compile('<P align=center><IMG\s.+?src="(.+?)".+?</P>', re.DOTALL).findall(link)

		for imglink in matchlink:
			if i < 10:
				addLink(" "+str(i)+". "+matchname[0],imglink,3,imglink.strip())
			else:
				addLink(str(i)+". "+matchname[0],imglink,3,imglink.strip())
			#xbmcgui.Window(xbmcgui.getCurrentWindowId()).setImage(imglink)
			if DEVELOP:
				print imglink
				print matchname

	if not DEVELOP:
		xbmcplugin.endOfDirectory(int(sys.argv[1]))


def SHOWIMAGE(url):
	link = GetHttpData(url)
	title = re.compile('<h1>(.+?)</h1>').findall(link)
	if DEVELOP:
		print url
	link = GetHttpData(url)
	matchlink = re.compile('<P align=center.+?<IMG.+?src="(.+?)".+?</.+?>').findall(link)
	for imglink in matchlink:
		addPicItems(title, imglink)
		#xbmcgui.Window(xbmcgui.getCurrentWindowId()).setImage(imglink)

def get_params():
	param=[]
	paramstring=sys.argv[2]
	if len(paramstring)>=2:
		params=sys.argv[2]
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

def addLink(name,url,mode,iconimage):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	if DEVELOP:
		print "addLink :" + urllib.unquote_plus(url) + "  &mode=" +str(mode)
	else:
		liz=xbmcgui.ListItem(name, iconImage="DefaultImage.png", thumbnailImage=iconimage)
		liz.setInfo(type='image', infoLabels={ "Title": name } )
		liz.setProperty('album_url',url)
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=False)
	return ok


def addDir(name,url,mode,iconimage,page,order):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&page="+str(page)+"&order="+str(order)
	ok=True
	if DEVELOP:
		print "addDir :"  + urllib.unquote_plus(url) + "  &name=" +str(name) + "  &mode=" +str(mode) + "  &page=" +str(page) + "  &order=" +str(order)
	else:
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

def main():
	if not DEVELOP:
		params=get_params()
	url=None
	name=None
	mode=None
	order=0
	page=1

	try:
		url=urllib.unquote_plus(params["url"])
	except:
		pass
	try:
		name=urllib.unquote_plus(params["name"])
	except:
		pass
	try:
		mode=int(params["mode"])
	except:
		pass
	try:
		order=int(params["order"])
	except:
		pass
	try:
		page=int(params["page"])
	except:
		pass

	if mode==None or url==None or len(url)<1:
		if DEVELOP:
			CATEGORIES(3)
			#IMAGELIST('http://ipad.91.com/content/2012-07-12/20120712222555923_1.shtml',1)
			DUOWANIMAGELIST('http://tu.duowan.com/news/g/00/98/22.html',1)
		else:
			# Read Password via a keyboard
			keyboard = xbmc.Keyboard("", heading = "Please type your password", hidden = True)
			keyboard.setHeading('Password') # optional
			keyboard.setHiddenInput(True) # optional
			keyboard.doModal()
			if (keyboard.isConfirmed()):
    				inputText = keyboard.getText()
 	   			# set password parameter
    				Password = inputText
				if inputText == "1234":
					LOGINOK = True
				else:
    					dialogInfo = xbmcgui.Dialog()
    					LoginMessage = "Wrong Password"
					LOGINOK = False
  	  				dialogInfo.ok("Password", LoginMessage)
				keyboard.setHiddenInput(False) # optional
				del keyboard
			else:
				return

			if LOGINOK:
				CATEGORIES(0)
			else:
				return

	elif mode==1:
		CATEGORIES(page)
                
	elif mode==2:
		IMAGELIST(url,page)

	elif mode==3:
		DUOWANIMAGELIST(url,page)

if __name__ == "__main__":
    main()

